<template>
  <div class="login-page">
    <div class="form-wrapper">
      <!--    <p class="form-title">{{$t('login.title')}}</p>-->
      <div class="logo-box">
        <div class="logo"></div>
      </div>
      <el-form
          ref="loginFormRef"
          label-position="top"
          :model="loginForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon>
        <el-form-item prop="phone" label-position="">
          <el-input size="large" v-model="loginForm.phone" :placeholder="$t('login.phonePla')">
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" label-position="">
          <el-input size="large" v-model="loginForm.code" :placeholder="$t('login.codePla')">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
          <el-button link type="primary" class="code-btn" :disabled="!loginForm.phone || getCodeLoading || downCount !== 0" @click="getValidateCode">{{codeStr}}</el-button>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="check">
            <span>{{$t('login.checkStr')}}<el-button link type="primary">{{$t('login.protocolStr')}}</el-button></span>
          </el-checkbox>
        </el-form-item>
        <div class="submit-btn">
          <el-button size="large" :disabled="!loginForm.phone || !loginForm.code || !check" type="danger" :loading="loginLoading" @click="handleLogin">{{$t('login.login')}}</el-button>
        </div>
      </el-form>
    </div>
  </div>
  <ChangeLocale @change="handleLocaleChange"></ChangeLocale>
</template>

<script setup>
import {ref} from 'vue'
import { Iphone, Message } from '@element-plus/icons-vue'
import {useRouter} from "vue-router";
import { useI18n } from 'vue-i18n';
import ChangeLocale from './components/locale/change-locale.vue'
import api from './api/index.js'
import common from "~/common/common.js";

const { t } = useI18n();
const router = useRouter()
const getCodeLoading = ref(false)
const loginLoading = ref(false)
const loginFormRef = ref()
const loginForm = ref({
  phone: '',
  code: '',
})
const codeStr = ref(t('login.codeStr'))
const downCount = ref(0)
const check = ref(false)
const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('login.phone_required')))
  } else {
    callback()
  }
}
const validateCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('login.code_required')))
  } else {
    callback()
  }
}
const rules = {
  phone: [
    { validator: validatePhone, trigger: 'blur' },
  ],
  code: [
    { validator: validateCode, trigger: 'blur' },
  ],
}
const handleLocaleChange = () => {
  if (downCount.value === 0) {
    codeStr.value = t('login.codeStr')
  }
}
let downInterval = null
const getValidateCode = () => {
  if (downCount.value !== 0 || getCodeLoading.value) {
    return
  }
  getCodeLoading.value = true
  api.getCode({
    mobile: loginForm.value.phone,
    scene: '1',
  }).then(res => {
    if (res.code === 0) {
      ElMessage.success('验证码发送成功')
      clearInterval(downInterval)
      downCount.value = 60
      downInterval = setInterval(() => {
        downCount.value--
        codeStr.value = `${downCount.value}${t('login.codeStr2')}`
        if (downCount.value <= 0) {
          downCount.value = 0
          clearInterval(downInterval)
          downInterval = null
          codeStr.value = t('login.codeStr')
        }
      }, 1000)
    } else {
      ElMessage.error('验证码发送失败')
    }
    getCodeLoading.value = false
  }).catch(e => {
    getCodeLoading.value = false
    ElMessage.error('验证码发送异常')
    console.log(e)
  })

}

const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    if (!check.value) {
      return
    }
    loginLoading.value = true
    api.login({
      mobile: loginForm.value.phone,
      code: loginForm.value.code,
    }).then(res => {
      loginLoading.value = false
      if (res.data && res.data.userId) {
        ElMessage.success('登录成功')
        common.setLocalUser({
          userId: res.data.userId + '',
        })
        router.replace('/index')
      } else {
        ElMessage.error(res.msg || '登录失败')
      }
    }).catch(e => {
      loginLoading.value = false
      ElMessage.error('登录异常')
    })
  } catch(e){
    console.log(e)
  }
}
</script>

<style scoped lang="scss">
.login-page{
  position: relative;
  height: 100%;
  width: 100%;
  background: url("./assets/images/login-bg.png") no-repeat;
  background-size: 100% 100%;
}
.form-wrapper{
  position: absolute;
  width: 378px;
  height: 325px;
  padding: 56px 66px 67px;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
  background: #fff;
  box-shadow: 0px 2px 6px 2px rgba(0,0,0,0.15);
  border-radius: 10px;
  .logo-box{
    position: relative;
    padding-bottom: 20px;
    text-align: center;
    .logo{
      display: inline-block;
      width: 67px;
      height: 61px;
      background-image: url("./assets/images/logo.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
  }
  }
  .form-title{
    padding: 20px 0;
    text-align: center;
  }
  .code-btn{
    position: absolute;
    right: 25px;
  }
  .submit-btn .el-button{
    width: 100%;
  }
}
.locale-box{
  position: absolute;
  right: 100px;
  top:100px;
}
</style>
